Skip to main content

Session Management

Session management ensures that a user's authenticated state is preserved across requests. It involves creating, storing, refreshing, and deleting sessions or tokens to maintain seamless access for users.

On Assemble Web, this is implemented using a stateless session approach.

Stateless

Session data (or a token) is stored in the browser's cookies. The cookie is sent with each request, allowing the session to be verified on the server. This method simplifies the architecture but requires careful implementation to maintain security.

Implementation

The stateless session management on Assemble Web follows these key steps:

  1. Generate and Store a Secret Key

A secret key is used to sign the session, ensuring data integrity and security. This is managed as an environment variable:

  • Set the SESSION_KEY environment variable with the current secret key.
  • Access this key in the app using the sessionKey variable from src/config/app.
  1. Encrypt and Decrypt Session Data

Encryption and decryption of session data are handled using a session management library.

  • The logic resides in src/utils/jwt.ts.
  • Assemble Web uses the jose library along with React's server-only package to ensure session management logic runs exclusively on the server.
  • The secret key is utilized to sign and verify sessions.
  1. Manage cookies using the Next.js cookies API.

Centralized cookie management is implemented in src/app/api/session/session.ts. This server-only file provides three primary functions:

  • createSession: Saves user information.
  • getSession: Retrieves user data. If the authToken has expired, it uses the refreshToken to obtain a new one. If neither token is valid, it returns null, requiring the user to log in again.
  • deleteSession: Deletes the session.

Client-Side and Server-Side Usage

On the client side, utility functions in src/utils/session.ts allow components to interact indirectly with the Next.js cookies API.

On the server side, the functions in src/app/api/session/session.ts can be used directly. For example, these can be called in Next.js middleware to validate user state for routing decisions.